package com.bocai.user.mapper;

import com.bocai.duobao.model.SimpleBetRecord;
import com.bocai.user.model.*;
import com.bocai.user.model.entity.BetDetail;
import com.bocai.user.model.entity.CodepayRecord;
import com.bocai.user.model.vo.SpendRecord;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.sql.Statement;
import java.util.List;

/**
 * @author create by VIC.Huang
 * @date 2018/1/22
 */
@Component
@Mapper
public interface UserMapper {
    @Select("select id, nick_name nickName, wx_name wxName, wx_head_img wxHeadImg, disable " +
            "from t_user where open_id = #{openid}")
    User selectUserByOpenId(@Param("openid") String openid);

    @Insert("insert into t_user(nick_name,wx_name,open_id,wx_head_img,fromuid) " +
            "values(#{nickName}, #{wxName}, #{openId}, #{wxHeadImg}, #{fromuid})")
    @SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty = "id", before = false, resultType = long.class)
    int insertWxUser(User user);

    @Select("select user_id userId, asset, frozen_asset frozenAsset from t_user_asset where user_id = #{userId}")
    UserAsset selectUserAsset(@Param("userId") Long userId);

    @Update("update t_user_asset set asset = asset + #{money}, frozen_asset = frozen_asset + #{frozenMoney} where user_id = #{userId}")
    int updateUserAsset(@Param("userId") Long userId, @Param("money") BigDecimal money, @Param("frozenMoney") BigDecimal frozenMoney);

    @Insert("insert into t_user_asset(user_id) values(#{userId})")
    int initUserAsset(@Param("userId") Long userId);

    @Insert("insert into t_spend_record(user_id, type, money) values(#{userId}, #{type}, #{money})")
    int insertSpendRecord(@Param("userId") Long userId, @Param("money") BigDecimal money, @Param("type") String spendType);

    @Select("<script>" +
            "select count(1) from t_db_bet_detail where user_id = #{userId}" +
            "<if test=\"winStatus != null\"> and win_status = #{winStatus}</if>" +
            "</script>")
    int countBetRecordsByUserId(@Param("userId") Long userId, @Param("winStatus") String winStatus);

    @Select("<script>" +
            "select db_game_id gameId, order_no orderNo, create_time betTime, db_game_list_img_path listImgPath, " +
            " db_game_title gameTitle, bet_num betNum, amount betAmount, per_price perPrice, issue_no issueNo, open_code openCode," +
            " win_status winStatus " +
            " from t_db_bet_detail where user_id = #{userId}" +
            " <if test=\"winStatus != null\"> and win_status = #{winStatus}</if>" +
            " order by id desc " +
            " limit #{page}, #{pageSize}" +
            "</script>")
    List<BetRecord> selectBetRecordsByUserId(@Param("userId") Long userId, @Param("winStatus") String winStatus,
                                             @Param("page") Integer page, @Param("pageSize") int pageSize);

    @Select("<script>" +
            "select tb.user_id userId, tu.nick_name nickName, tu.wx_head_img headImgPath, tb.amount amount, tb.db_game_title gameTitle, tb.create_time betTime " +
            " from t_db_bet_detail tb" +
            " join t_user tu on tb.user_id = tu.id " +
            " where 1 = 1" +
            " <if test=\"gameId != null\"> and tb.db_game_id = #{gameId}</if> " +
            " <if test=\"winStatus != null\"> and tb.win_status = #{winStatus}</if>" +
            " order by tb.id desc limit #{page}, #{pageSize}" +
            "</script>")
    List<SimpleBetRecord> selectLatestBetRecords(@Param("gameId") Long gameId, @Param("winStatus") String winStatus, @Param("page") Integer page, @Param("pageSize") int pageSize);

    @Select("select id, db_game_id dbGameId, user_id userId, bet_num betNum, amount, per_price perPrice, per_win_price perWinPrice," +
            " order_no orderNo, issue_no issueNo, open_code openCode, open_result openResult, win_status winStatus, win_price winPrice " +
            " from t_db_bet_detail where issue_no = #{issueNo}")
    List<BetDetail> selectBetDetailsByIssueNo(@Param("issueNo") String issueNo);

    @Update("update t_db_open_record set finish_flag = 'YES' where id = #{id}")
    int updateOpenRecordFinished(@Param("id") Long id);

    @Update("update t_db_bet_detail set open_code = #{openCode}, win_status = #{winStatus}, win_price = #{prizeMoney} where id = #{id}")
    int updateBetDetail(@Param("id") Long id, @Param("openCode") String openCode, @Param("winStatus") String winStatus, @Param("prizeMoney") BigDecimal prizeMoney);

    @Select("<script>" +
            "select count(1) " +
            " from t_db_bet_detail tb" +
            " join t_user tu on tb.user_id = tu.id " +
            " where 1 = 1" +
            " <if test=\"gameId != null\"> and tb.db_game_id = #{gameId}</if> " +
            " <if test=\"winStatus != null\"> and tb.win_status = #{winStatus}</if>" +
            "</script>")
    int countLatestBetRecords(@Param("gameId") Long gameId, @Param("winStatus") String winStatus);

    @Select("<script>select count(1) from t_db_bet_detail where user_id = #{userId} " +
            "<if test=\"dateStr != null\"> and DATE(create_time) = #{dateStr}</if>" +
            "<if test=\"winStatus != null\"> and win_status = #{winStatus}</if>" +
            "</script>")
    int selectBetFrequency(@Param("userId") Long userId, @Param("dateStr") String date, @Param("winStatus") String winStatus);

    @Select("<script>" +
            "select " +
            " type, money, create_time time " +
            " from t_spend_record where user_id = #{userId} " +
            "<if test=\"types != null\"> and type in " +
            "<foreach collection=\"types\" index=\"index\" item=\"type\" open=\"(\" separator=\",\" close=\")\">" +
            "#{type}" +
            "</foreach>" +
            "</if>" +
            " order by id desc limit #{page}, #{pageSize}" +
            "</script>")
    List<SpendRecord> selectSpendRecrod(@Param("userId") Long userId, @Param("types") List<String> types, @Param("page") int page, @Param("pageSize") int pageSize);

    @Select("<script>" +
            "select count(1) " +
            " from t_spend_record where user_id = #{userId} " +
            "<if test=\"types != null\"> and type in " +
            "<foreach collection=\"types\" index=\"index\" item=\"type\" open=\"(\" separator=\",\" close=\")\">" +
            "#{type}" +
            "</foreach>" +
            "</if>" +
            "</script>")
    long countSpendRecord(@Param("userId") Long userId, @Param("types") List<String> types);

    @Insert("insert into t_codepay_record(pay_id,money,price,type,pay_no,param,pay_time,pay_tag,sign) " +
            "values(#{pay_id},#{money},#{price},#{type},#{pay_no},#{param},#{pay_time},#{pay_tag},#{sign})")
    int insertCodepayRecord(CodepayRecord codepayRecord);

    @Insert("insert into t_withdraw_record(user_id,money,qrcode) " +
            "values(#{userId},#{money},#{qrcode})")
    int insertWithdrawRecord(@Param("userId") Long userId, @Param("money") BigDecimal withdrawMoney, @Param("qrcode") String qrcode);

    @Select("select nick_name nickName, wx_name wxName, wx_head_img wxHeadImg, mobile, withdraw_collect_qrcode withdrawCollectQrcode, fromuid " +
            "from t_user where id = #{userId}")
    User selectUserById(@Param("userId") Long userId);

    @Update("update t_user set withdraw_collect_qrcode = #{qrcode} where id = #{userId} and withdraw_collect_qrcode != #{qrcode}")
    int updateWithdrawCollectQrcode(@Param("userId") Long userId, @Param("qrcode") String qrcode);

    @Update("update t_user set nick_name = #{nickName}, wx_name = #{wxName}, wx_head_img = #{wxHeadImg} where id = #{id}")
    int updateWxUser(User userModel);

    @Select("<script>" +
            "select sum(m) from (" +
            " select sum(money) m from t_commission_record where user_id = #{userId} " +
            "   <if test='date != null'> and DATE(create_time) = #{date}</if>" +
            " UNION ALL " +
            " select sum(money) m from t_payback_record where user_id = #{userId} " +
            "   <if test='date != null'> and DATE(create_time) = #{date}</if>" +
            ") temp " +
            "</script>")
    BigDecimal sumCommissionAndPayback(@Param("userId") Long userId, @Param("date") String date);

    @Insert("insert into t_commission_record(user_id,from_user_id,from_user_name,money) values(#{userId},#{fromUserId},#{fromUserName},#{money})")
    int insertCommissionRecord(CommissionRecord cr);

    @Select("select count(1) from t_commission_record where user_id = #{userId}")
    int countCommissionRecords(Long userId);

    @Select("select user_id userId, from_user_id fromUserId, from_user_name fromUserName, money, create_time time" +
            " from t_commission_record where user_id = #{userId} order by id desc limit #{start}, #{count}")
    List<CommissionRecord> selectCommissionRecords(@Param("userId") Long userId, @Param("start") Integer start, @Param("count") Integer count);

    @Select("select from_user_name userName, sum(money) totalMoney, tu.create_time registerTime" +
            " from t_commission_record tcr" +
            " join t_user tu on tcr.from_user_id = tu.id" +
            " where tcr.user_id = #{userId} group by tcr.from_user_id")
    List<CommissionPlayer> selectCommissionPlayer(@Param("userId") Long userId);

    @Select("select id, nick_name nickName, wx_name wxName, wx_head_img wxHeadImg, disable, passwd " +
            "from t_user where nick_name = #{username}")
    User selectUserByName(@Param("username") String username);

    @Insert("insert into t_user(nick_name, passwd, fromuid) " +
            "values(#{nickName}, #{passwd}, #{fromuid})")
    @SelectKey(statement = "SELECT LAST_INSERT_ID()", keyProperty = "id", before = false, resultType = long.class)
    int insertUser(User user);

    @Insert("insert into t_payback_record(user_id,money) values(#{userId},#{money})")
    int insertPaybackRecord(PaybackRecord pr);

    @Select("select count(1) from t_payback_record where user_id = #{userId}")
    int countPaybackRecords(Long userId);

    @Select("select user_id userId, money, create_time time from t_payback_record " +
            "where user_id = #{userId} order by id desc limit #{start}, #{count}")
    List<PaybackRecord> selectPaybackRecords(@Param("userId") Long userId, @Param("start") Integer start, @Param("count") Integer count);

    @Select("select count(1) from t_codepay_record where pay_no = #{payNo}")
    int countCodepayRecord(@Param("payNo") String payNo);
}
